import axios from 'axios'
import appStore from '@/store'
import type { AxiosRequestConfig, AxiosInstance } from 'axios'

export interface Result<T> {
  data: T
  code: number
  msg: string
}

const config: AxiosRequestConfig = {
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 10000
}

class Request {
  instance: AxiosInstance
  constructor() {
    this.instance = axios.create(config)

    this.instance.interceptors.request.use(
      config => {
        const { token } = appStore.useUserStore
        if (token) {
          config.headers.Authorization = token
        }
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    this.instance.interceptors.response.use(
      response => {
        switch (response.data?.code) {
          case 401:
            appStore.useUserStore.setToken('')
            break
          case 403:
            // 403 无权限
            break
          case 404:
            // 404 未找到
            break
          case 500:
            // 500 服务器错误
            window.$message.error(response.data.msg)
            break
          default:
            break
        }
        return response.data
      },
      error => {
        window.$message.error('系统繁忙，请稍后重试')
        return Promise.reject(error)
      }
    )
  }
  get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<Result<T>> {
    return this.instance({ url, method: 'GET', params, ...config })
  }
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<Result<T>> {
    return this.instance({ url, method: 'POST', data, ...config })
  }
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<Result<T>> {
    return this.instance({ url, method: 'DELETE', ...config })
  }
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<Result<T>> {
    return this.instance({ url, method: 'PUT', data, ...config })
  }
}

const request = new Request()
export default request
